import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  SearchBar,
  Swiper,
  Grid,
  Image,
  Card,
  Button,
  Toast
} from 'antd-mobile';
import { getBannerPlaceholder, getProductPlaceholder } from '../../utils/imageUtils';
import './Home.css';
import { useRequest } from 'ahooks';
import { getCategories, getBanners, getHotProducts } from '../../api/store';

// 前台首页
const Home = () => {
  const navigate = useNavigate();
  const [banners, setBanners] = useState([]);
  const [hotProducts, setHotProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);

  const { runAsync: fetchProducts } = useRequest(getHotProducts, { manual: true });
  const { runAsync: fetchCategories } = useRequest(getCategories, { manual: true });
  const { runAsync: fetchBanner } = useRequest(getBanners, { manual: true });

  const { userId } = JSON.parse(localStorage.getItem('userInfo')) || {};
  const fetchData = async () => {
    setLoading(true);
    try {
      const [bannersData, categoriesData, productsData] = await Promise.all([
        fetchBanner({ params: { id: userId } }),
        fetchCategories({ params: { id: userId } }),
        fetchProducts({ params: { id: userId } })
      ]);
      setBanners(bannersData);
      console.log(productsData)
      setCategories(categoriesData);
      setHotProducts(productsData);
    } catch (error) {
      console.error('获取首页数据失败', error);
      Toast.show({
        icon: 'fail',
        content: '获取数据失败，请稍后重试',
      });
    }
    setLoading(false);
  }
  // 获取首页数据
  useEffect(() => {
    fetchData();
  }, []);

  // 处理搜索
  const handleSearch = (value) => {
    navigate(`/search?keyword=${encodeURIComponent(value)}`);
  };

  // 处理跳转到分类页
  const handleCategoryClick = (category) => {
    navigate(`/category/${category.id}`);
  };

  // 处理跳转到商品详情
  const handleProductClick = (product) => {
    navigate(`/product/${product.id}`);
  };

  // 渲染轮播图
  const renderBanners = () => {
    if (!banners || banners.length === 0) {
      return null;
    }
    return (
      <Swiper autoplay loop>
        {banners.map(banner => (
          <Swiper.Item key={banner.id} onClick={() => navigate(banner.link)}>
            <Image src={banner.image} fit='cover' />
          </Swiper.Item>
        ))}
      </Swiper>
    );
  };

  // 渲染分类
  const renderCategories = () => {
    return (
      <div className="home-categories">
        <Grid columns={4} gap={8}>
          {categories.map(category => (
            <Grid.Item key={category.id} onClick={() => handleCategoryClick(category)}>
              <div className="category-item">
                <div className="category-icon">{category.icon}</div>
                <div className="category-name">{category.name}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    );
  };

  // 渲染热门商品
  const renderHotProducts = () => {
    return (
      <div className="home-products">
        <div className="section-title">热门商品</div>
        <Grid columns={2} gap={10}>
          {hotProducts.map(product => (
            <Grid.Item key={product.id}>
              <Card
                className="product-card"
                onClick={() => handleProductClick(product)}
              >
                <Image src={product.images?.[0] || getProductPlaceholder(product.name)} fit='cover' />
                <div className="product-info">
                  <div className="product-name">{product.name}</div>
                  <div className="product-price">
                    <span className="price">¥{product.price}</span>
                    {product.originalPrice && (
                      <span className="original-price">¥{product.originalPrice}</span>
                    )}
                  </div>
                  <div className="product-sales">已售 {product.sales}</div>
                </div>
              </Card>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    );
  };

  return (
    <div className="home-container">
      {/* 搜索栏 */}
      <div className="search-container">
        <SearchBar
          placeholder='搜索商品'
          onSearch={handleSearch}
        />
      </div>

      {/* 内容区域 */}
      <div className="home-content">
        {/* 轮播图 */}
        {renderBanners()}

        {/* 分类导航 */}
        {renderCategories()}

        {/* 热门商品 */}
        {renderHotProducts()}
      </div>
    </div>
  );
};

export default Home; 